// 学习小组相关API接口
import axios from 'axios'
import type { StudyGroup, GroupMember, GroupActivity } from '../types/group'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API请求错误:', error)
    return Promise.reject(error)
  }
)

// 获取所有学习小组
export const getAllGroups = async (params: {
  page?: number
  pageSize?: number
  categoryId?: number
  keyword?: string
  sortBy?: 'popular' | 'latest' | 'name'
} = {}): Promise<{ content: StudyGroup[], totalElements: number, totalPages: number }> => {
  return await api.get('/groups', { params })
}

// 根据分类获取学习小组
export const getGroupsByCategory = async (categoryId: number, params: {
  page?: number
  pageSize?: number
} = {}): Promise<{ content: StudyGroup[], totalElements: number, totalPages: number }> => {
  return await api.get(`/groups/category/${categoryId}`, { params })
}

// 搜索学习小组
export const searchGroups = async (keyword: string, params: {
  page?: number
  pageSize?: number
} = {}): Promise<{ content: StudyGroup[], totalElements: number, totalPages: number }> => {
  return await api.get('/groups/search', { params: { keyword, ...params } })
}

// 获取热门学习小组
export const getPopularGroups = async (params: {
  page?: number
  pageSize?: number
} = {}): Promise<{ content: StudyGroup[], totalElements: number, totalPages: number }> => {
  return await api.get('/groups/popular', { params })
}

// 获取最新学习小组
export const getLatestGroups = async (params: {
  page?: number
  pageSize?: number
} = {}): Promise<{ content: StudyGroup[], totalElements: number, totalPages: number }> => {
  return await api.get('/groups/latest', { params })
}

// 获取学习小组详情
export const getGroupDetail = async (groupId: number): Promise<StudyGroup> => {
  return await api.get(`/groups/${groupId}`)
}

// 创建学习小组
export const createGroup = async (data: {
  name: string
  description: string
  categoryId?: number
  maxMembers?: number
  isPublic?: boolean
}): Promise<StudyGroup> => {
  return await api.post('/groups', data)
}

// 更新学习小组
export const updateGroup = async (groupId: number, data: {
  name?: string
  description?: string
  categoryId?: number
  maxMembers?: number
  isPublic?: boolean
}): Promise<StudyGroup> => {
  return await api.put(`/groups/${groupId}`, data)
}

// 删除学习小组
export const deleteGroup = async (groupId: number): Promise<void> => {
  return await api.delete(`/groups/${groupId}`)
}

// 加入学习小组
export const joinGroup = async (groupId: number): Promise<void> => {
  return await api.post(`/groups/${groupId}/join`)
}

// 退出学习小组
export const leaveGroup = async (groupId: number): Promise<void> => {
  return await api.post(`/groups/${groupId}/leave`)
}

// 获取用户加入的学习小组
export const getUserGroups = async (userId: number): Promise<StudyGroup[]> => {
  return await api.get(`/groups/user/${userId}`)
}

// 检查用户是否已加入学习小组
export const isUserJoined = async (groupId: number): Promise<boolean> => {
  return await api.get(`/groups/${groupId}/joined`)
}

// 获取学习小组（别名，兼容性）
export const getGroups = getAllGroups

// 获取小组成员
export const getGroupMembers = async (groupId: number): Promise<GroupMember[]> => {
  return await api.get(`/groups/${groupId}/members`)
}

// 创建小组活动
export const createGroupActivity = async (groupId: number, data: {
  title: string
  description: string
  activityType: string
  startTime: string
  endTime?: string
}): Promise<GroupActivity> => {
  return await api.post(`/groups/${groupId}/activities`, data)
}

// 获取小组活动
export const getGroupActivities = async (groupId: number, params: {
  page?: number
  pageSize?: number
} = {}): Promise<{ content: GroupActivity[], totalElements: number, totalPages: number }> => {
  return await api.get(`/groups/${groupId}/activities`, { params })
}